package cn.tedu;

import cn.utiles.JDBCUtiles;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;


public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解决乱码
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        //获取表单信息
        String username = req.getParameter("username");
        String password = req.getParameter("password");


        //校验
        //用户名校验
        if(username==null||username.trim().length()==0){
            req.setAttribute("msg","用户名不能为空");
            req.getRequestDispatcher(req.getContextPath()+"/login.jsp").forward(req,resp);
            return;
        }
        if(password==null||password.trim().length()==0) {
            req.setAttribute("msg", "密码不能为空");
            req.getRequestDispatcher( req.getContextPath()+"/login.jsp").forward(req, resp);
            return;
        }

        boolean login=LoginServlet.login(username,password);
        if (login){

            resp.getWriter().write("3s后跳转");

            resp.setHeader("refresh", "3;url="+req.getContextPath()+"/index.jsp");
        }else {
            resp.getWriter().write("登陆失败");
        }



    }
    public static boolean login(String username, String password) {
        String password1=null;
        try {
            Connection conn=JDBCUtiles.getConn();
            PreparedStatement ps=conn.prepareStatement(
                    "select password from user where username=?;");
            ps.setString(1,username);
            ResultSet rs=ps.executeQuery();

            while(rs.next()){
                password1=(String) rs.getObject("password");
            }

            JDBCUtiles.closeAll(ps,rs,conn);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        if(password.equals(password1)){
            return true;

        }else{
            return false;
        }
    }


    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
